package com.tjh1.transaction;

import com.tjh1.util.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @ClassName TransactionTest
 * @Description : 事务处理
 * @Author tang'jia'hao
 * @Date 2021/9/21 19:10
 * @Version 1.0
 **/
public class TransactionTest {

    @Test
    public void testUpdate() {

        String sql1 = "update user_table set balance = balance - 100 where user = ?";
        JDBCUtils.update(sql1, "AA");


        String sql2 = "update user_table set balance = balance + 100 where user = ?";
        JDBCUtils.update(sql2, "BB");

        System.out.println("转账成功");
    }

    @Test
    public void testUpdateWithTx() {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();

            // 取消数据的自动提交
            conn.setAutoCommit(false);

            String sql1 = "update user_table set balance = balance - 100 where user = ?";
            JDBCUtils.update(conn, sql1, "AA");

//            System.out.println(120 / 0);

            String sql2 = "update user_table set balance = balance + 100 where user = ?";
            JDBCUtils.update(conn, sql2, "BB");

            System.out.println("转账成功");

            // 提交数据
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if (conn != null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            JDBCUtils.closeResource(conn, null);
        }
    }

    // 隔离级别
    @Test
    public void testTransactionSelect() throws Exception {

        Connection conn = JDBCUtils.getConnection();
        System.out.println(conn.getTransactionIsolation());
        conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        conn.setAutoCommit(false);

        String sql = "select user,password,balance from user_table where user = ?";
        User user = JDBCUtils.getInstance(conn, User.class, sql, "CC");

        System.out.println("user = " + user);
    }

    @Test
    public void testTransactionUpdate() throws Exception {

        Connection conn = JDBCUtils.getConnection();
        conn.setAutoCommit(false);

        String sql = "update user_table set balance = ? where user = ?";
        JDBCUtils.update(conn, sql, 500, "CC");
        Thread.sleep(15000);
        System.out.println("修改结束");
    }

}
